home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 881 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.6 KB

  1. Path: ix.netcom.com!netnews
  2. From: miker3@ix.netcom.com (Mike Rubenstein)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Error?
  5. Date: Mon, 08 Jan 1996 02:03:04 GMT
  6. Organization: Netcom
  7. Message-ID: <30f075e8.169549440@nntp.ix.netcom.com>
  8. References: <4cpaov$241@news.rrz.uni-koeln.de>
  9. NNTP-Posting-Host: ix-dc14-13.ix.netcom.com
  10. X-NETCOM-Date: Sun Jan 07  6:02:44 PM PST 1996
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. a2867001@smail.rrz.Uni-Koeln.DE (Lars Kaderali) wrote:
  14.  
  15. |>Hey folks! Need some help - I tried the following program in c++ on
  16. an
  17. |>ibm pc:
  18. |>
  19. |>=======================================
  20. |>
  21. |>//test
  22. |>#include <iostream.h>
  23. |>float a,b;
  24. |>main()
  25. |>{
  26. |>  a=-1.0; b=0.1;
  27. |>  while (a<1.1)
  28. |>  {
  29. |>    cout<<a<<endl;
  30. |>    a+=b;
  31. |>  }
  32. |>}
  33. |>
  34. |>=======================================
  35. |>
  36. |>which returns:
  37. |>
  38. |>-1
  39. |>-0.9
  40. |>-0.8
  41. |>-0.7
  42. |>-0.6
  43. |>-0.5
  44. |>-0.4
  45. |>-0.3
  46. |>-0.2
  47. |>-0.1
  48. |>(so far as expected, but then:)
  49. |>7.450581e-08     < ==== ??????????????
  50. |>0.1
  51. |>0.2
  52. |>0.3
  53. |>0.4
  54. |>0.5
  55. |>0.6
  56. |>0.7
  57. |>0.8
  58. |>0.9
  59. |>1
  60. |>
  61. |>How come this 7.450581e-08 happens instead of 0.0 ?????
  62.  
  63. Welcome to the world of binary floating point.  On most machines
  64. floating point numbers are stored in binary.  In binary 0.1 cannot be
  65. expressed exactly with a finite number of digits.  The computer does
  66. the best it can, but actually uses a number that's just close.
  67.  
  68. This can cause other anomolies.  In some cases your loop may go one
  69. step further or less than you expect.
  70.  
  71. Using double will make the numbers more accurate, but still not exact
  72. and the same kind of think will happen.  Here, the number printed
  73. where you expect 0 will be smaller, but probably still not 0.
  74.  
  75. Michael M Rubenstein
  76.